import { useEffect, useState } from "react";
import "./../assets/scss/App.scss";

import { GreeterClient } from "../grpc/HelloworldServiceClientPb";
import { HelloRequest } from "../grpc/helloworld_pb";

import api from '../api'

import axios from 'axios'

import styles from './App.module.css'




const readFile = (file) => {
  return new Promise<string>((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = () => {
      resolve(reader.result as string)
    }
    reader.readAsText(file)
  })
}

const parseProtoFile = async (file) => {
  const packageReg = /package.*?(.*?);/
  const serviceReg = /service(.*?){.*?}/gs
  // const serviceReg = /service(.*?){.*?rpc (.*?)\((.*?)\) returns \((.*?)\).*?}/gs
  const methodReg = /rpc(.*?)\((.*?)\).*?returns.*?\((.*?)\)/gs

  const grpcObj = {}
  // 文件的字符串
  const fileStr = await readFile(file)
  // proto 包名
  const protoPackName = fileStr.match(packageReg)[1].trim()
  grpcObj[protoPackName] = {}
  // 服务数组
  const serviceName = [...fileStr.matchAll(serviceReg)]
  serviceName.forEach(serviceItem => {
    const client = serviceItem[1].trim()
    // 服务的方法名,请求类,响应类
    const clientMethods = [...serviceItem[0].matchAll(methodReg)]
    grpcObj[protoPackName][client] = {}
    clientMethods.forEach(methodObj => {
      grpcObj[protoPackName][client][methodObj[1].trim()] = [methodObj[2].trim(), methodObj[3].trim()]
    })
  })
  return grpcObj
}




//////拦截器必须要实现intercept这个接口函数
//const SimpleUnaryInterceptor = {
//  intercept: (request: Request<HelloRequest, any>, invoker) => {
//  // const reqMsg = request.getRequestMessage();
//  // request.getMetadata()

//  // After the RPC returns successfully, update the response.
//    return invoker(request).then((response: UnaryResponse<HelloRequest, HelloResponse>) => {
//    return response;
//  });
//  }
//};
//const options = {
//  unaryInterceptors: [SimpleUnaryInterceptor]
//}

const backendUrl = "/api";
const greeterClientOrigin = new GreeterClient(backendUrl, null);

const App = (props: {}) => {

  useEffect(() => {

    // const greeterRequestOrigin = new HelloRequest()
    // greeterRequestOrigin.setName('feedoom')
    // greeterClientOrigin.sayHello(greeterRequestOrigin, null).then(res => console.log('-------------\n这是原生grpc请求:', res.toObject(), '\n---------------'))

    // api.greeter.sayHello({name: 'feedoom'}).then(res => console.log('这是封装sayHello的方法', res)).catch(err => console.log(err, 'err'))

    // api.greeter.errRequest({message: 'this is a error request'}).then(console.log).catch(err => console.log('这是一条错误请求', err))

    // api.check.getStudent({name: 'feedoom'}).then(res => console.log('这是封装getStudents的方法', res))

    // const timeoutRequest = api.greeter.timeoutRequest()
    // timeoutRequest.then(res => console.log('这是超时的请求', res))
    // setTimeout(() => {
    //   const res = timeoutRequest.cancel()
    //   console.log(res)
    // }, 5000)

    // api.greeter.sayMap({name: 'arch', age: '22'}).then(res => console.log('这是封装sayMap的方法', res))



  }, []);

  const [grpcObj, setGrpcObj] = useState(null)
  const [currentPackage, setCurrentPackage] = useState('')
  const [clients, setClients] = useState([])
  const [currentClient, setCurrentClient] = useState('')
  const [methods, setMethods] = useState([])
  const [currentMethod, setCurrentMethod] = useState('')


  const handleFile = async (e) => {
    const grpcObj = await parseProtoFile(e.target.files[0])
    const packeName = Object.keys(grpcObj)[0]
    const clients = Object.keys(grpcObj[packeName])
    const currentClient = clients[0]
    const methods = Object.keys(grpcObj[packeName][currentClient])

    setGrpcObj(grpcObj)
    setCurrentPackage(packeName)
    setClients(clients)
    setCurrentClient(currentClient)
    setMethods(methods)
    setCurrentMethod(methods[0])

    const form = new FormData();
    form.append('file', e.target.files[0]);
    console.log(form, e.target.files[0])
    axios.post('/upload/file', form).then(res => console.log(res)).catch(err => console.log(err))

    // fetch('/upload/file', {
    //   method: 'post',
    //   body: form
    // }).then(res => res.json()).then(res => console.log(res))
  }

  useEffect(() => {
    // axios.get('/upload/hello').then(res => console.log(res))
    // const script = document.createElement('script');
 //    script.type = 'text/javascript';
 //    script.src = 'http://192.168.0.9:8856/dist/js/main.js';

 //    document.body.appendChild(script);
  }, [])

  return (
    <div className="app">
      <h1>Hello World!</h1>
      <p>Foo to the barz</p>
      <div className={styles.grpcBox}>
        <div className='row'>
          <input type='text'></input>
          <input type='file' onChange={handleFile} />
        </div>
        <div>
          <select onChange={(e) => {setCurrentClient(e.target.value) ;console.log(e.target.value)}}>
            {clients.map(item => {
              return <option key={item} value={item}>{item}</option>
            })}
          </select>
          <select onChange={(e) => {setCurrentMethod(e.target.value) ;console.log(e.target.value)}}>
            {methods.map(item => {
              return <option key={item} value={item}>{item}</option>
            })}
          </select>
        </div>
        <textarea></textarea>
        <div>
          timeout: <input></input>
          <button>send</button>
        </div>
        <div>
          <textarea></textarea>
          <textarea></textarea>
        </div>
      </div>
    </div>
  )
};

export default App;

